#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;

#define NUM 5

enum
{
    NORMAL,
    ERROR
};

class ThreadData{
public:
    //输入的
    string _name;
    int _id;
    uint64_t _createTime;

    //返回的
    int _status;
    //char arr[n]
    int _top;
    int _result;

public:
    ThreadData(const string& name,int id, time_t createTime, int top) : _name(name),_id(id),_createTime(createTime)
                                                              ,_status(NORMAL),_top(top),_result(0){

    }

    ~ThreadData(){

    }
};

void *thread_run(void *args){

    //char *name = (char *)args;

    ThreadData *td = static_cast<ThreadData *>(args);

    // while(1){
    //     cout << "thread_run, thread name:" << td->_name << " thread id:" << td->_id << " thread createTime:" << td->_createTime << endl;
    //     ////进程退出
    //     // exit(1);
    //     sleep(1);
    //     //线程退出
    //     break;
    // }

    for (int i = 1; i <= td->_top; i++){
        td->_result += i;
    }
    cout << td->_name << " cal done! result:" << td->_result << endl;


    //线程退出  --  终止调用的线程
    //pthread_exit(td);
    return td;

    //线程取消
    //                  -1
    //pthread_exit(PTHREAD_CANCELED);
}

int main(){

    // //创建线程
    // pthread_t t;
    // pthread_create(&t, nullptr, thread_run, nullptr);

    // while(1){
    //     cout << "main thread, thread_run id:" << t << endl;
    //     sleep(1);
    // }

    cout << "-----create thread-----" << endl;
    // 创建线程
    pthread_t tids[NUM];
    for (int i = 0; i < NUM;i++){

        //在外部定义临时tname会导致所有的线程name相同
        //  线程看到的是同一个地址，create时把tname的地址传入，但是后续更改了tname创建新的线程，所有的线程共用一个tname导致所有线程的那么都和最后创建的线程一样
        //char tname[64];

        //动态开辟tname，保证每个线程用的都是不同的地址
        char *tname = new char[64];
        snprintf(tname, 64, "thread-%d", i + 1);

        ThreadData *td = new ThreadData(tname, i + 1, time(nullptr),10*i);

        pthread_create(tids + i, nullptr, thread_run, td);

        delete tname;

        sleep(1);
    }

    cout << "-----wait thread-----" << endl;
    //等待线程
    void *ret = nullptr;
    for (int i = 0; i < NUM;i++){
        int n = pthread_join(tids[i], &ret);
        if (n != 0)
        {
            cerr << "pthread_join error" << endl;
        }
        //cout << "thread quit:" << (uint64_t)ret << endl;
        ThreadData *td = static_cast<ThreadData *>(ret);
        if (td->_status == NORMAL)
        {
            cout << td->_name << ": 计算0~" << td->_top << "累加之和 result:" << td->_result << endl;
        }

        delete td;

        sleep(1);
    }

        // while(1){
        //     cout << "main thread----------" << endl;
        //     sleep(1);
        // }

    cout << "all thread quit" << endl;

    return 0;
}









